package com.shmilyou.dissertationmanagement.web;
/* Created with 岂止是一丝涟漪     530060499@qq.com    2018/11/23 */

import com.shmilyou.dissertationmanagement.biz.PatentService;
import com.shmilyou.dissertationmanagement.biz.SoftwareCopyrightService;
import com.shmilyou.dissertationmanagement.biz.ThesisService;
import com.shmilyou.dissertationmanagement.biz.UserService;
import com.shmilyou.dissertationmanagement.domain.User;
import com.shmilyou.dissertationmanagement.resolver.LoginUser;
import com.shmilyou.dissertationmanagement.tools.Utils;
import com.shmilyou.dissertationmanagement.utils.ConfigUtils;
import com.shmilyou.dissertationmanagement.utils.Constant;
import com.shmilyou.dissertationmanagement.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    private final Logger log = LoggerFactory.getLogger(IndexController.class);

    private final UserService userService;
    private final ThesisService thesisService;
    private final PatentService patentService;
    private final SoftwareCopyrightService softwareCopyrightService;


    @Autowired
    public IndexController(UserService userService, ThesisService thesisService, PatentService patentService,
                           SoftwareCopyrightService softwareCopyrightService) {
        this.userService = userService;
        this.thesisService = thesisService;
        this.patentService = patentService;
        this.softwareCopyrightService = softwareCopyrightService;
    }

    @RequestMapping(value = {"/", "/index", ""})
    public ModelAndView index() {
        //load data
        int thesisCount = thesisService.getCount();
        int patentCount = patentService.getCount();
        int softwareCopyrightCount = softwareCopyrightService.getCount();
        double total = thesisCount + patentCount + softwareCopyrightCount;
        if (total < 1) {
            total = 1.0;
        }
        DecimalFormat df = new DecimalFormat("#.##");

        //generate json
        ModelAndView modelAndView = new ModelAndView("index");
        List<Map> data = new ArrayList<>(3);
        Map<String, Object> data1 = new HashMap();
        data1.put("item", "论文");
        data1.put("percent", Double.parseDouble(df.format(thesisCount / total)));
        data1.put("count", thesisCount);
        data.add(data1);

        Map<String, Object> data2 = new HashMap();
        data2.put("item", "专利");
        data2.put("percent", Double.parseDouble(df.format(patentCount / total)));
        data2.put("count", patentCount);
        data.add(data2);

        Map<String, Object> data3 = new HashMap();
        data3.put("item", "软著");
        data3.put("percent", Double.parseDouble(df.format(softwareCopyrightCount / total)));
        data3.put("count", softwareCopyrightCount);
        data.add(data3);
        modelAndView.addObject("data", Utils.generateJson(data));
        return modelAndView;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> login(User user, Boolean anonymous, HttpServletRequest request,
                                                     HttpServletResponse response) throws IOException {
        if (anonymous != null && anonymous) {
            //匿名登录
            if (ConfigUtils.anonymous) {
                LoginUser instance = LoginUser.getInstance();
                instance.setNickname("匿名登录");
                instance.setId(-1);
                request.getSession().setAttribute(Constant.LOGIN_USER, instance);
                return WebUtils.success();
            }
        }
        if (user == null || StringUtils.isEmpty(user.getEmail()) || StringUtils.isEmpty(user.getPassword())) {
            return WebUtils.failure();
        }
        User result = userService.login(user);
        if (result != null) {
            LoginUser loginUser = new LoginUser();
            loginUser.setId(result.getId());
            loginUser.setEmail(result.getEmail());
            loginUser.setNickname(result.getNickname());
            request.getSession().setAttribute(Constant.LOGIN_USER, loginUser);

            //跳转至未登录前访问的页面
            String requestURI = (String) request.getSession().getAttribute("requestURI");
            if (requestURI != null) {
                return WebUtils.success(requestURI);
            }
            return WebUtils.success();
        }
        return WebUtils.failure();
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search() {
        return "search";
    }
}
